import React, { useEffect, useState, useRef } from "react";
import { Button } from "react-vant";
import { useNavigate } from "react-router-dom";
import { Fire, MapMarked } from "@react-vant/icons";
import city from "../utils/city.json";
import axios from "axios";
import IndexBars from "../components/IndexBars";
type Props = {};

const Start = (props: Props) => {
  const [startData, setStartData] = useState([]);
  const valInp: any = useRef();
  const [cityVal, setCityVal] = useState("");
  const [cityList, setCityList] = useState(city.cityList);
  const navigate = useNavigate();
  useEffect(() => {
    (async () => {
      let res = await axios.get(
        "https://m.ly.com/trainbffapi/searchHotCity?mid=&pid=432&refId=478807627&traceId=T16819950604922841&ts=1681995076409&ver=1.0.0&abtkey=89d052c7-473a-4cd1-b1ae-b683984693b7&section=20&selectCity=1"
      );
      setStartData(res.data.data.result);
    })();
  }, []);

  //进页面被选择的城市高亮
  const [val, setVal] = useState(localStorage.getItem("start") || "");
  const [i, setI] = useState("");
  useEffect(() => {
    startData.forEach((item: any, index: any) => {
      if (item.name === val) {
        setI(index);
      }
    });
  }, [startData]);
  //点击城市存储
  const btnStart = (name: any) => {
    localStorage.setItem("start", name);
    navigate("/index/home");
  };
  //inp
  const inpChange = (e: any) => {
    setCityVal(e.target.value);
  };
  //搜索
  const btnSearch = () => {
    const arr1 = startData.filter((item: any) => {
      return item.name.includes(cityVal);
    });
    setStartData(arr1);
  };
  //跳转地图页面
  const goMap = () => {
    console.log(123);
    navigate("/maps");
  };
  return (
    <div className="start">
      <header>
        <span onClick={goMap}>
          <MapMarked />
        </span>
        <input ref={valInp} type={"text"} onChange={inpChange} />
        <Button onClick={btnSearch} type="primary">
          搜索
        </Button>
      </header>
      <main>
        <div style={{ width: "100%", height: "30px" }}></div>
        <div className="title">
          <Fire color="red" />
          <span>热门城市</span>
          <Fire color="red" />
        </div>
        <div className="city_box">
          {startData &&
            startData.map((item: any, index: any) => {
              return (
                <span
                  className={i === index ? "on" : ""}
                  onClick={() => btnStart(item.name)}
                  key={index}
                >
                  {item.name}
                </span>
              );
            })}
        </div>
        <div className="box">
          <IndexBars cityList={cityList} flag={true} />
        </div>
      </main>
    </div>
  );
};

export default Start;
